package com.example.chinesechess.presentation.ui.component

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import android.graphics.Paint
import android.graphics.Typeface
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.chinesechess.domain.model.ChessPiece
import com.example.chinesechess.domain.model.Position
import com.example.chinesechess.domain.model.Side
import com.example.chinesechess.presentation.ui.theme.boardBackground
import com.example.chinesechess.presentation.ui.theme.boardHighlight
import com.example.chinesechess.presentation.ui.theme.boardLastMove
import com.example.chinesechess.presentation.ui.theme.boardLine
import com.example.chinesechess.presentation.ui.theme.boardSelected
import com.example.chinesechess.presentation.ui.theme.pieceBlack
import com.example.chinesechess.presentation.ui.theme.pieceOutline
import com.example.chinesechess.presentation.ui.theme.pieceRed
import com.example.chinesechess.presentation.viewmodel.GameViewModel

@Composable
fun ChessBoard(
    modifier: Modifier = Modifier,
    viewModel: GameViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    
    Box(
        modifier = modifier
            .aspectRatio(9f/10f)
            .background(boardBackground)
    ) {
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(Unit) {
                    detectTapGestures { offset ->
                        val boardWidth = size.width
                        val boardHeight = size.height
                        val cellWidth = boardWidth / 8  // 改为8等分
                        val cellHeight = boardHeight / 9 // 改为9等分
                        
                        // 计算最接近的交点
                        val col = ((offset.x + (cellWidth / 2)) / cellWidth).toInt().coerceIn(0, 8)
                        val row = ((offset.y + (cellHeight / 2)) / cellHeight).toInt().coerceIn(0, 9)
                        
                        viewModel.onSquareSelected(Position(col, row))
                    }
                }
        ) {
            // Draw board
            drawBoard()
            
            // Draw highlighted positions (valid moves)
            uiState.validMoves.forEach { position ->
                drawHighlightedPosition(position, boardHighlight)
            }
            
            // Draw last move
            uiState.lastMove?.let { move ->
                drawHighlightedPosition(move.from, boardLastMove)
                drawHighlightedPosition(move.to, boardLastMove)
            }
            
            // Draw selected position
            uiState.selectedPosition?.let { position ->
                drawHighlightedPosition(position, boardSelected)
            }
            
            // Draw all pieces
            uiState.pieces.forEach { piece ->
                drawChessPiece(piece)
            }
        }
    }
}

private fun DrawScope.drawHighlightedPosition(position: Position, color: Color) {
    val cellWidth = size.width / 8  // 改为8等分，因为有9条线
    val cellHeight = size.height / 9 // 改为9等分，因为有10条线
    
    val center = Offset(
        position.x * cellWidth,
        position.y * cellHeight
    )
    
    drawCircle(
        color = color,
        radius = minOf(cellWidth, cellHeight) / 2.5f,
        center = center
    )
}

private fun DrawScope.drawBoard() {
    val boardWidth = size.width
    val boardHeight = size.height
    
    // 重新计算单元格宽高，确保棋子位于正确的位置
    val cellWidth = boardWidth / 8  // 改为8等分，因为有9条线
    val cellHeight = boardHeight / 9 // 改为9等分，因为有10条线
    
    // 绘制棋盘边框
    drawRect(
        color = boardLine,
        topLeft = Offset(0f, 0f),
        size = Size(boardWidth, boardHeight),
        style = Stroke(width = 4f)
    )
    
    // 绘制纵向线(9条)
    for (i in 0..8) {
        drawLine(
            color = boardLine,
            start = Offset(i * cellWidth, 0f),
            end = Offset(i * cellWidth, boardHeight),
            strokeWidth = 2f
        )
    }
    
    // 绘制横向线(10条)
    for (i in 0..9) {
        // 河界处线条略粗
        val strokeWidth = if (i == 4 || i == 5) 3f else 2f
        drawLine(
            color = boardLine,
            start = Offset(0f, i * cellHeight),
            end = Offset(boardWidth, i * cellHeight),
            strokeWidth = strokeWidth
        )
    }
    
    // 绘制"楚河汉界"区域
    drawRect(
        color = Color(0x33A9A9A9),
        topLeft = Offset(0f, 4 * cellHeight),
        size = Size(boardWidth, cellHeight),
    )
    
    // 绘制九宫格斜线
    // 上方九宫格
    drawLine(
        color = boardLine,
        start = Offset(3 * cellWidth, 0f),
        end = Offset(5 * cellWidth, 2 * cellHeight),
        strokeWidth = 2f
    )
    
    drawLine(
        color = boardLine,
        start = Offset(5 * cellWidth, 0f),
        end = Offset(3 * cellWidth, 2 * cellHeight),
        strokeWidth = 2f
    )
    
    // 下方九宫格
    drawLine(
        color = boardLine,
        start = Offset(3 * cellWidth, 7 * cellHeight),
        end = Offset(5 * cellWidth, 9 * cellHeight),
        strokeWidth = 2f
    )
    
    drawLine(
        color = boardLine,
        start = Offset(5 * cellWidth, 7 * cellHeight),
        end = Offset(3 * cellWidth, 9 * cellHeight),
        strokeWidth = 2f
    )
    
    // 绘制兵卒位置和炮位的标记
    // 哨位标记点（这里简化处理，实际棋盘会有更复杂的星位标记）
    val positions = listOf(
        // 兵卒位置
        Pair(1, 2), Pair(7, 2), // 黑方炮位
        Pair(0, 3), Pair(2, 3), Pair(4, 3), Pair(6, 3), Pair(8, 3), // 黑方兵位
        Pair(1, 7), Pair(7, 7), // 红方炮位
        Pair(0, 6), Pair(2, 6), Pair(4, 6), Pair(6, 6), Pair(8, 6)  // 红方兵位
    )
    
    positions.forEach { (x, y) ->
        drawSmallCross(x, y, cellWidth, cellHeight)
    }
}

private fun DrawScope.drawSmallCross(x: Int, y: Int, cellWidth: Float, cellHeight: Float) {
    // 交点位置
    val centerX = x * cellWidth
    val centerY = y * cellHeight
    val lineLength = minOf(cellWidth, cellHeight) / 8f
    
    // 绘制小十字的四个方向线段
    // 左
    if (x > 0) {
        drawLine(
            color = boardLine,
            start = Offset(centerX - lineLength, centerY),
            end = Offset(centerX, centerY),
            strokeWidth = 2f
        )
    }
    
    // 右
    if (x < 8) {
        drawLine(
            color = boardLine,
            start = Offset(centerX, centerY),
            end = Offset(centerX + lineLength, centerY),
            strokeWidth = 2f
        )
    }
    
    // 上
    if (y > 0) {
        drawLine(
            color = boardLine,
            start = Offset(centerX, centerY - lineLength),
            end = Offset(centerX, centerY),
            strokeWidth = 2f
        )
    }
    
    // 下
    if (y < 9) {
        drawLine(
            color = boardLine,
            start = Offset(centerX, centerY),
            end = Offset(centerX, centerY + lineLength),
            strokeWidth = 2f
        )
    }
}

private fun DrawScope.drawChessPiece(piece: ChessPiece) {
    val cellWidth = size.width / 8  // 改为8等分，因为有9条线
    val cellHeight = size.height / 9 // 改为9等分，因为有10条线
    
    val center = Offset(
        piece.position.x * cellWidth,
        piece.position.y * cellHeight
    )
    
    val radius = minOf(cellWidth, cellHeight) / 2.2f
    
    // Piece background (ivory color)
    drawCircle(
        color = Color(0xFFF5F5DC),
        radius = radius,
        center = center
    )
    
    // Piece outline
    val pieceColor = if (piece.side == Side.RED) pieceRed else pieceBlack
    drawCircle(
        color = pieceColor,
        radius = radius,
        center = center,
        style = Stroke(width = 3f)
    )
    
    // Draw the piece text (Chinese character)
    drawIntoCanvas { canvas ->
        val paint = Paint()
        paint.textAlign = Paint.Align.CENTER
        paint.textSize = radius * 1.2f
        paint.color = pieceColor.toArgb()
        paint.typeface = Typeface.DEFAULT_BOLD
        paint.isFakeBoldText = true
        paint.isAntiAlias = true
        
        // Center text vertically by adjusting with textHeight/2
        val textHeight = paint.fontMetrics.bottom - paint.fontMetrics.top
        val verticalOffset = textHeight / 4
        
        canvas.nativeCanvas.drawText(
            piece.getDisplayName(),
            center.x,
            center.y + verticalOffset,
            paint
        )
    }
} 